package com.lyh.dt.filter;


import com.lyh.dt.server.TransactionClient;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.common.extension.Activate;
import org.apache.dubbo.rpc.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author liuyuhong
 */
@Activate(group = {"PROVIDER","CONSUMER"})
public class DubboDtFilter implements Filter {

    private final static Logger logger = LoggerFactory.getLogger(DubboDtFilter.class);

    @Override
    public Result invoke(Invoker<?> invoker, Invocation invocation) throws RpcException {
        logger.info("开始执行DubboDtFilter...");
        Result result = null;
        try {
            if (RpcContext.getContext().isConsumerSide()) {
                setAttachment(invoker,invocation);
            }else{
                getAttachment(invoker, invocation);
            }
            result = invoker.invoke(invocation);
        }catch (Exception e){
            logger.error("dubbo DubboDtFilter执行出现异常", e);
        }
        return result;
    }

    private void setAttachment(Invoker<?> invoker,Invocation invocation) {
        try {
            String groupId = TransactionClient.threadLocalGroupId.get();
            if(StringUtils.isNotBlank(groupId)){
                RpcContext.getContext()
                        .setInvoker(invoker)
                        .setInvocation(invocation)
                        .setAttachment("groupId",groupId);
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
    }

    private void getAttachment(Invoker<?> invoker, Invocation invocation) {
        try {
            String groupId = RpcContext.getContext().
                    setInvoker(invoker).setInvocation(invocation).getAttachment("groupId");
            if(StringUtils.isNotBlank(groupId)){
                TransactionClient.threadLocalGroupId.set(groupId);
            }
        }catch(Exception e) {
            e.printStackTrace();
        }
    }
}
